package com.community.controller;

import com.community.pojo.User;
import com.community.service.AdminService;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;

@Controller
public class UpdatePasswordController {
    private final AdminService adminService;
    @Autowired
    public UpdatePasswordController(AdminService adminService) {
        this.adminService = adminService;
    }
    @GetMapping("/update-password-form")
    public String updateUserFormController(){
        return "updatePasswordForm";
    }
    @PostMapping("/update-password")
    public String updateUserController(@RequestParam("oldPassword") String oldPassword,
                                       @RequestParam("newPassword1") String newPassword1,
                                       @RequestParam("newPassword2") String newPassword2,
                                       Model model, HttpSession session) {
        if(oldPassword.equals("")||newPassword1.equals("")||newPassword2.equals("")){
            model.addAttribute("message", "密码不允许为空! " );
            return "updatePasswordForm";
        }
        User user = (User) session.getAttribute("user");
        if(oldPassword.equals(newPassword1)){
            model.addAttribute("message","新密码不能与旧密码相同! ");
            return "updatePasswordForm";
        }
        if(oldPassword.equals(user.getPassword())){
            if(newPassword1.equals(newPassword2)){
                int n= adminService.updatePassword(user.getUserId(),newPassword1);
                if(n==1){
                    model.addAttribute("message","密码更新成功! ");
                }else{
                    model.addAttribute("message","密码更新失败! ");
                    return "updatePasswordForm";
                }
            }else{
                model.addAttribute("message","两次更新的密码不一致! ");
                return "updatePasswordForm";
            }
        }else{
            model.addAttribute("message","旧密码错误! ");
            return "updatePasswordForm";
        }
        return "updatePasswordResult";
    }

}
